package qinggui.mlz.smsservice.infrastructure;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class SmsTemplate {

    /**
     * 向指定手机号发送验证码/任意模板短信
     *
     * @param mobile 手机号
     * @param code   验证码（如需多位可扩展）
     * @return "OK" 表示成功，其余为错误码
     */
    private static final String ACCESS_KEY_ID = "LTAI5tGAXnceSAq4wHADR5B2";
    private static final String ACCESS_KEY_SECRET      = "40DskVVNTMFaTGr69WdsgLlTs6lpu4";
    private static final String REGION   = "cn-shenzhen";
    private static final String SIGN_NAME    = "清规";
    private static final String TEMPLATE_CODE    = "SMS_短信服务码";
    public String send(String mobile, String code) {
        // 初始化阿里云短信服务客户端
        DefaultProfile profile = DefaultProfile.getProfile(REGION, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        // 构造短信发送请求
        SendSmsRequest req = new SendSmsRequest();
        req.setPhoneNumbers(mobile);
        req.setSignName(SIGN_NAME);
        req.setTemplateCode(TEMPLATE_CODE);
        req.setTemplateParam("{\"code\":\"" + code + "\"}");
        try {
            // 发送短信并返回结果码
            SendSmsResponse rsp = client.getAcsResponse(req);
            return rsp.getCode();   // "OK" 或具体错误码
        } catch (ClientException e) {
            // 记录日志、告警、限流等
            return e.getErrCode();
        }
    }
}
